package com.zz.server;

import com.zz.server.config.TunnelServerConfig;
import com.zz.common.exception.TunnelException;
import com.zz.server.factory.ServerBootstrapFactory;
import com.zz.common.tunnel.Tunnel;
import com.zz.common.tunnel.TunnelHelper;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

@Slf4j
public class TunnelServerApplication implements Tunnel {


    private final ServerBootstrap bootstrap;

    private final NioEventLoopGroup serverBossGroup;

    private final NioEventLoopGroup serverWorkGroup;

    public TunnelServerApplication() {
        serverBossGroup = new NioEventLoopGroup();
        serverWorkGroup = new NioEventLoopGroup();
        bootstrap = ServerBootstrapFactory.createServerBootstrap(serverBossGroup, serverWorkGroup);
    }


    @Override
    public void start() {
        try {
            bootstrap.bind(TunnelServerConfig.getInstance().getServerBind(), TunnelServerConfig.getInstance().getServerPort()).get();
            log.info("proxy server start on port " + TunnelServerConfig.getInstance().getServerPort());
        } catch (Exception ex) {
            throw new TunnelException("启动绑定端口异常！error message:{}", ex.getMessage());
        }

    }

    @Override
    public void stop() {
        serverBossGroup.shutdownGracefully();
        serverWorkGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        TunnelHelper.start(Arrays.asList(new TunnelServerApplication(), new TunnelHttpApplication()));
    }
}
